<style>

</style>

<template>
    <p>
        <a-space>
            <TrainSelectView v-model:value="queryParam.trainCode" width="200px"></TrainSelectView>
            <a-button type="primary" @click="handleQuery()">查询</a-button>
            <a-button type="primary" @click="handleQuery()">刷新</a-button>
            <a-button type="primary" @click="onAdd">新增</a-button>
        </a-space>
    </p>
    <a-table 
        :dataSource="trainStations" 
        :columns="columns" 
        :pagination="pagination" 
        :loading="loading"
        @change="handleTableChange" 
    >
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
                <a-space>
                    <a-popconfirm
                        title="删除后不可恢复，确认删除?"
                        @confirm="onDelete(record)"
                        ok-text="确认"
                        cancel-text="取消"
                    >
                        <a style="color: red">删除</a>
                    </a-popconfirm>
                
                    <a @click="onEdit(record)">编辑</a>
                </a-space>
            </template>
        </template>
    </a-table>
    <a-modal v-model:visible="visible" title="火车车站" @ok="handleOk" ok-text="确认" cancel-text="取消">
        <a-form :model="train" :label-col="{span: 4}" :wrapper-col="{span: 14}">
            <a-form-item label="火车编号">
                <!-- 下拉框的组件 -->
                <TrainSelectView v-model="trainStation.trainCode"/>
            </a-form-item>
            <a-form-item label="站序">
                <a-input v-model:value="trainStation.stationIndex"/>
            </a-form-item>
            <a-form-item label="站名">
                <StationSelectView v-model:value="trainStation.name"></StationSelectView>
            </a-form-item>
            <a-form-item label="站名拼音">
              <a-input v-model:value="trainStation.namePinyin" disabled/>
            </a-form-item>
            <a-form-item label="进站时间">
              <a-time-picker v-model:value="trainStation.inTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
            </a-form-item>
            <a-form-item label="出战时间">
              <a-time-picker v-model:value="trainStation.outTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
            </a-form-item>
            <a-form-item label="停站时长">
              <a-time-picker v-model:value="trainStation.stopTime" valueFormat="HH:mm:ss" placeholder="请选择时间" disabled/>
            </a-form-item>
            <a-form-item label="里程（公里）">
              <a-input v-model:value="trainStation.km" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
import { defineComponent,ref,onMounted,watch} from 'vue';
import TrainSelectView from '@/components/TrainSelectView.vue'
import { notification } from 'ant-design-vue';
import {pinyin} from 'pinyin-pro'
import axios from 'axios';
import dayjs from 'dayjs'
import StationSelectView from '@/components/StationSelectView.vue';

export default defineComponent({
  name: "trainStation-view",
  components:{
    TrainSelectView,
    StationSelectView
},
  setup() {
    // 展示模态窗的标签的定义
    const visible = ref(false);
    const loading = ref(false);
    const queryParam = ref({
        trainCode: null
    })

    // 定义车站对象
    let trainStation = ref({
        id: undefined,
        trainCode: undefined,
        stationIndex: undefined,
        name: undefined,
        namePinyin: undefined,
        inTime: undefined,
        outTime: undefined,
        stopTime: undefined,
        km: undefined,
        createTime: undefined,
        updateTime: undefined
    });

    const trainStations = ref([]);
    
    const columns = [
        {
            title: '车次编号',
            dataIndex: 'trainCode',
            key: 'trainCode',
        },
        {
            title: '站序',
            dataIndex: 'stationIndex',
            key: 'stationIndex',
        },
        {
            title: '站名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '站名拼音',
            dataIndex: 'namePinyin',
            key: 'namePinyin',
        },
        {
            title: '进站时间',
            dataIndex: 'inTime',
            key: 'inTime',
        },
        {
            title: '出战时间',
            dataIndex: 'outTime',
            key: 'outTime',
        },
        {
            title: '停站时长',
            dataIndex: 'stopTime',
            key: 'stopTime',
        },
        {
            title: '里程（公里）',
            dataIndex: 'km',
            key: 'km',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
        }
    ];

    // watch计算函数监听name属性的变化
    watch(() => trainStation.value.name, () => {
        if(window.Tool.isNotEmpty(trainStation.value.name)){
            trainStation.value.namePinyin = pinyin(trainStation.value.name,{toneType:'none'}).replaceAll(" ","")
        }else{
            trainStation.value.namePinyin = ""
        }
    }, {immediate:true})

    let pagination =ref({
        total: 0,
        current: 1,
        pageSize: 10,
    });

     // 自动计算停车时长
     watch(() => trainStation.value.inTime, ()=>{
      let diff = dayjs(trainStation.value.outTime, 'HH:mm:ss').diff(dayjs(trainStation.value.inTime, 'HH:mm:ss'), 'seconds');
      trainStation.value.stopTime = dayjs('00:00:00', 'HH:mm:ss').second(diff).format('HH:mm:ss');
    }, {immediate: true});

    // 自动计算停车时长
    watch(() => trainStation.value.outTime, ()=>{
      let diff = dayjs(trainStation.value.outTime, 'HH:mm:ss').diff(dayjs(trainStation.value.inTime, 'HH:mm:ss'), 'seconds');
      trainStation.value.stopTime = dayjs('00:00:00', 'HH:mm:ss').second(diff).format('HH:mm:ss');
    }, {immediate: true});

    // 点击新增展示模态窗的函数方法
    const onAdd = () => {
        console.log("add")
        visible.value = true;
        trainStation.value = {}
    };

    // 点击编辑展示模态窗的函数方法
    const onEdit = (record) => {
        console.log("edit")
        trainStation.value = window.Tool.copy(record)
        visible.value = true;
    };

     // 点击删除按钮的函数方法
    const onDelete = (record) => {
        axios.delete("/business/admin/train-station/delete/"+record.id)
        .then( response => {
            console.log(response.data.data)
            if(response.data.data){
                notification.success({ description: '删除成功' });
                // 刷新页面
                handleQuery()
            }
        })
        .catch( error => {
            notification.error({ description:  error.response.data.data});
        })
    }

    // 点击模态窗的ok按钮执行的函数方法
    const handleOk = e => {
        axios.post("/business/admin/train-station/save", trainStation.value)
            .then( response => {
                let respData = response.data
                console.log(respData)
                if(respData.data){
                    notification.success({ description: '保存成功！' });
                    // 设置为false，关闭模态窗
                    visible.value = false;
                    // 调用列表查询的接口，刷新数据
                    handleQuery()
                }else{
                    notification.error({ description: respData.errorMessage });
                }
            })
            .catch( error => {
                let errData = error.response.data
                console.log(errData)
                notification.error({ description: errData.data });
            })
    };

    // 车站信息列表查询的方法
    const handleQuery = e => {
        // 刷新时候不带参数的判断
        if(!e){
            e = {
                page: 1,
                limit: pagination.value.pageSize
            }
        }
        // 开启loading效果
        loading.value = true
        axios.get("/business/admin/train-station/query",
            {
                params:{
                    page: e.page,
                    limit: e.limit,
                    trainCode: queryParam.value.trainCode
                }
            })
            .then( response => {
                // 关闭loading效果
                loading.value = false
                let respData = response.data
                let trainStationDataList = respData.data.dataList
                let total = respData.data.total
                let currentPage = respData.data.currentPage
                let pageSize = respData.data.pageSize
                trainStations.value = trainStationDataList
                console.log("查询前")
                console.log(JSON.stringify(trainStation.value))
                console.log("查询后")
                // 分页控件的设置
                pagination.value.current = currentPage
                pagination.value.pageSize = pageSize
                pagination.value.total = total
            })
            .catch( error => {
                // 关闭loading效果
                loading.value = false
                let errData = error.response.data
                console.log(errData)
                notification.error({ description: errData.data });
            })
    };

    // 页码的点击事件
    const handleTableChange = (pagination) => {
        console.log("pagination:",pagination.value)
        // 调用车站列表查询方法
        handleQuery({
            page: pagination.current,
            limit: pagination.pageSize
        })
    };

    // 钩子函数，页面初始化的时候执行
    onMounted(() => {
        handleQuery({
            page: pagination.value.current,
            limit: pagination.value.pageSize
        })
    });


    return {
        visible,
        loading,
        queryParam,
        trainStation,
        trainStations,
        columns,
        pagination,
        onAdd,
        onEdit,
        onDelete,
        handleOk,
        handleQuery,
        handleTableChange
    };
  },
});
</script>